package repository

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

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

type MembersRepository struct {
	db *sql.DB
}

func NewMembersRepository(db *sql.DB) *MembersRepository {
	return &MembersRepository{db: db}
}

func (r *MembersRepository) GetMembers(ctx context.Context) ([]models.Member, error) {
	query := `
		SELECT id, name_ko, name_en, degree, affiliation, email, is_advisor, display_order, created_at
		FROM members
		ORDER BY display_order ASC, id ASC
	`
	rows, err := r.db.QueryContext(ctx, query)
	if err != nil {
		return nil, fmt.Errorf("query members: %w", err)
	}
	defer rows.Close()

	var members []models.Member
	for rows.Next() {
		var m models.Member
		if err := rows.Scan(
			&m.ID, &m.NameKo, &m.NameEn, &m.Degree,
			&m.Affiliation, &m.Email, &m.IsAdvisor, &m.DisplayOrder, &m.CreatedAt,
		); err != nil {
			return nil, fmt.Errorf("scan member: %w", err)
		}
		members = append(members, m)
	}
	return members, rows.Err()
}

func (r *MembersRepository) CreateMember(ctx context.Context, m models.Member) (int, error) {
	res, err := r.db.ExecContext(ctx, `
		INSERT INTO members (name_ko, name_en, degree, affiliation, email, is_advisor, display_order)
		VALUES (?, ?, ?, ?, ?, ?, ?)
	`, m.NameKo, m.NameEn, m.Degree, m.Affiliation, m.Email, m.IsAdvisor, m.DisplayOrder)
	if err != nil {
		return 0, fmt.Errorf("insert member: %w", err)
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func (r *MembersRepository) UpdateMember(ctx context.Context, id int, m models.Member) error {
	res, err := r.db.ExecContext(ctx, `
		UPDATE members
		SET name_ko = ?, name_en = ?, degree = ?, affiliation = ?, email = ?, is_advisor = ?, display_order = ?
		WHERE id = ?
	`, m.NameKo, m.NameEn, m.Degree, m.Affiliation, m.Email, m.IsAdvisor, m.DisplayOrder, id)
	if err != nil {
		return fmt.Errorf("update member: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

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

func (r *MembersRepository) GetAlumni(ctx context.Context) ([]models.Alumnus, error) {
	query := `
		SELECT id, name_ko, name_en, degree, graduated_at, major, current_position, created_at
		FROM alumni
		ORDER BY graduated_at DESC, id ASC
	`
	rows, err := r.db.QueryContext(ctx, query)
	if err != nil {
		return nil, fmt.Errorf("query alumni: %w", err)
	}
	defer rows.Close()

	var alumni []models.Alumnus
	for rows.Next() {
		var a models.Alumnus
		if err := rows.Scan(
			&a.ID, &a.NameKo, &a.NameEn, &a.Degree,
			&a.GraduatedAt, &a.Major, &a.CurrentPosition, &a.CreatedAt,
		); err != nil {
			return nil, fmt.Errorf("scan alumnus: %w", err)
		}
		alumni = append(alumni, a)
	}
	return alumni, rows.Err()
}

func (r *MembersRepository) CreateAlumnus(ctx context.Context, a models.Alumnus) (int, error) {
	res, err := r.db.ExecContext(ctx, `
		INSERT INTO alumni (name_ko, name_en, degree, graduated_at, major, current_position)
		VALUES (?, ?, ?, ?, ?, ?)
	`, a.NameKo, a.NameEn, a.Degree, a.GraduatedAt, a.Major, a.CurrentPosition)
	if err != nil {
		return 0, fmt.Errorf("insert alumnus: %w", err)
	}
	id, err := res.LastInsertId()
	return int(id), err
}

func (r *MembersRepository) UpdateAlumnus(ctx context.Context, id int, a models.Alumnus) error {
	res, err := r.db.ExecContext(ctx, `
		UPDATE alumni
		SET name_ko = ?, name_en = ?, degree = ?, graduated_at = ?, major = ?, current_position = ?
		WHERE id = ?
	`, a.NameKo, a.NameEn, a.Degree, a.GraduatedAt, a.Major, a.CurrentPosition, id)
	if err != nil {
		return fmt.Errorf("update alumnus: %w", err)
	}
	rows, err := res.RowsAffected()
	if err == nil && rows == 0 {
		return sql.ErrNoRows
	}
	return err
}

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