package repository

import (
	"context"
	"database/sql"
	"encoding/json"
	"fmt"

	"git.godopu.com/lab/landing_page/backend/internal/models"
)

type HomeRepository struct {
	db *sql.DB
}

func NewHomeRepository(db *sql.DB) *HomeRepository {
	return &HomeRepository{db: db}
}

func (r *HomeRepository) GetResearchProjects(ctx context.Context) ([]models.ResearchProject, error) {
	query := `
		SELECT id, slug, title, abstract, keywords, organization, standards_org, period, funder, created_at, updated_at
		FROM research_projects
		ORDER BY id ASC
	`
	rows, err := r.db.QueryContext(ctx, query)
	if err != nil {
		return nil, fmt.Errorf("query research projects: %w", err)
	}
	defer rows.Close()

	var projects []models.ResearchProject
	for rows.Next() {
		var p models.ResearchProject
		var kwJSON string
		err := rows.Scan(
			&p.ID, &p.Slug, &p.Title, &p.Abstract, &kwJSON,
			&p.Organization, &p.StandardsOrg, &p.Period, &p.Funder,
			&p.CreatedAt, &p.UpdatedAt,
		)
		if err != nil {
			return nil, fmt.Errorf("scan research project: %w", err)
		}
		if kwJSON != "" {
			_ = json.Unmarshal([]byte(kwJSON), &p.Keywords)
		}
		if p.Keywords == nil {
			p.Keywords = []string{}
		}
		projects = append(projects, p)
	}
	if err := rows.Err(); err != nil {
		return nil, err
	}
	return projects, nil
}

func (r *HomeRepository) CreateResearchProject(ctx context.Context, p models.ResearchProject) (int, error) {
	kwBytes, _ := json.Marshal(p.Keywords)
	if p.Keywords == nil {
		kwBytes = []byte("[]")
	}
	res, err := r.db.ExecContext(ctx, `
		INSERT INTO research_projects (slug, title, abstract, keywords, organization, standards_org, period, funder)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?)
	`, p.Slug, p.Title, p.Abstract, string(kwBytes), p.Organization, p.StandardsOrg, p.Period, p.Funder)
	if err != nil {
		return 0, fmt.Errorf("insert research project: %w", err)
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func (r *HomeRepository) UpdateResearchProject(ctx context.Context, id int, p models.ResearchProject) error {
	kwBytes, _ := json.Marshal(p.Keywords)
	if p.Keywords == nil {
		kwBytes = []byte("[]")
	}
	res, err := r.db.ExecContext(ctx, `
		UPDATE research_projects
		SET slug = ?, title = ?, abstract = ?, keywords = ?, organization = ?, standards_org = ?, period = ?, funder = ?, updated_at = CURRENT_TIMESTAMP
		WHERE id = ?
	`, p.Slug, p.Title, p.Abstract, string(kwBytes), p.Organization, p.StandardsOrg, p.Period, p.Funder, id)
	if err != nil {
		return fmt.Errorf("update research project: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

func (r *HomeRepository) DeleteResearchProject(ctx context.Context, id int) error {
	res, err := r.db.ExecContext(ctx, `DELETE FROM research_projects WHERE id = ?`, id)
	if err != nil {
		return fmt.Errorf("delete research project: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

func (r *HomeRepository) GetResearchAreas(ctx context.Context) ([]models.ResearchArea, error) {
	query := `
		SELECT id, name_en, name_kr, display_order
		FROM research_areas
		ORDER BY display_order ASC, id ASC
	`
	rows, err := r.db.QueryContext(ctx, query)
	if err != nil {
		return nil, fmt.Errorf("query research areas: %w", err)
	}
	defer rows.Close()

	var areas []models.ResearchArea
	for rows.Next() {
		var a models.ResearchArea
		if err := rows.Scan(&a.ID, &a.NameEn, &a.NameKr, &a.DisplayOrder); err != nil {
			return nil, fmt.Errorf("scan research area: %w", err)
		}
		areas = append(areas, a)
	}
	return areas, rows.Err()
}

func (r *HomeRepository) CreateResearchArea(ctx context.Context, a models.ResearchArea) (int, error) {
	tx, err := r.db.BeginTx(ctx, nil)
	if err != nil {
		return 0, fmt.Errorf("begin tx: %w", err)
	}
	defer tx.Rollback()

	if a.DisplayOrder > 0 {
		// Shift existing research areas with display_order >= target order by +1
		_, err = tx.ExecContext(ctx, `
			UPDATE research_areas
			SET display_order = display_order + 1
			WHERE display_order >= ?
		`, a.DisplayOrder)
		if err != nil {
			return 0, fmt.Errorf("shift research areas display_order: %w", err)
		}
	} else {
		var maxOrder sql.NullInt64
		_ = tx.QueryRowContext(ctx, `SELECT MAX(display_order) FROM research_areas`).Scan(&maxOrder)
		if maxOrder.Valid {
			a.DisplayOrder = int(maxOrder.Int64) + 1
		} else {
			a.DisplayOrder = 1
		}
	}

	res, err := tx.ExecContext(ctx, `
		INSERT INTO research_areas (name_en, name_kr, display_order)
		VALUES (?, ?, ?)
	`, a.NameEn, a.NameKr, a.DisplayOrder)
	if err != nil {
		return 0, fmt.Errorf("insert research area: %w", err)
	}

	if err := tx.Commit(); err != nil {
		return 0, fmt.Errorf("commit tx: %w", err)
	}

	id, err := res.LastInsertId()
	return int(id), err
}

func (r *HomeRepository) UpdateResearchArea(ctx context.Context, id int, a models.ResearchArea) error {
	tx, err := r.db.BeginTx(ctx, nil)
	if err != nil {
		return fmt.Errorf("begin tx: %w", err)
	}
	defer tx.Rollback()

	var oldOrder int
	err = tx.QueryRowContext(ctx, `SELECT display_order FROM research_areas WHERE id = ?`, id).Scan(&oldOrder)
	if err != nil {
		if err == sql.ErrNoRows {
			return sql.ErrNoRows
		}
		return fmt.Errorf("get old display_order: %w", err)
	}

	if a.DisplayOrder > 0 && a.DisplayOrder != oldOrder {
		if oldOrder < a.DisplayOrder {
			_, err = tx.ExecContext(ctx, `
				UPDATE research_areas
				SET display_order = display_order - 1
				WHERE display_order > ? AND display_order <= ? AND id != ?
			`, oldOrder, a.DisplayOrder, id)
		} else {
			_, err = tx.ExecContext(ctx, `
				UPDATE research_areas
				SET display_order = display_order + 1
				WHERE display_order >= ? AND display_order < ? AND id != ?
			`, a.DisplayOrder, oldOrder, id)
		}
		if err != nil {
			return fmt.Errorf("shift research areas display_order on update: %w", err)
		}
	}

	res, err := tx.ExecContext(ctx, `
		UPDATE research_areas
		SET name_en = ?, name_kr = ?, display_order = ?
		WHERE id = ?
	`, a.NameEn, a.NameKr, a.DisplayOrder, id)
	if err != nil {
		return fmt.Errorf("update research area: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return tx.Commit()
}

func (r *HomeRepository) DeleteResearchArea(ctx context.Context, id int) error {
	res, err := r.db.ExecContext(ctx, `DELETE FROM research_areas WHERE id = ?`, id)
	if err != nil {
		return fmt.Errorf("delete research area: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

func (r *HomeRepository) GetStatsSummary(ctx context.Context) (*models.StatsSummary, error) {
	var summary models.StatsSummary

	err := r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM publications WHERE category = 'intl-journal-conf'").Scan(&summary.IntlPublications)
	if err != nil {
		return nil, fmt.Errorf("count intl publications: %w", err)
	}

	err = r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM standard_documents").Scan(&summary.StandardizationDocs)
	if err != nil {
		return nil, fmt.Errorf("count standard documents: %w", err)
	}

	err = r.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM patents").Scan(&summary.Patents)
	if err != nil {
		return nil, fmt.Errorf("count patents: %w", err)
	}

	return &summary, nil
}
