package repository

import (
	"context"
	"errors"
	"time"

	"github.com/google/uuid"
	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
	"backend/internal/models"
)

type ClientRepository struct {
	db *pgxpool.Pool
}

func NewClientRepository(db *pgxpool.Pool) *ClientRepository {
	return &ClientRepository{db: db}
}

func (r *ClientRepository) FindByUsername(ctx context.Context, username string) (*models.Client, error) {
	query := `
		SELECT id, name, email, phone, address, username, password, status, is_active, 
		       last_login, created_at, updated_at, deleted_at
		FROM clients
		WHERE username = $1 AND deleted_at IS NULL
	`

	var client models.Client
	err := r.db.QueryRow(ctx, query, username).Scan(
		&client.ID,
		&client.Name,
		&client.Email,
		&client.Phone,
		&client.Address,
		&client.Username,
		&client.Password,
		&client.Status,
		&client.IsActive,
		&client.LastLogin,
		&client.CreatedAt,
		&client.UpdatedAt,
		&client.DeletedAt,
	)

	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return nil, errors.New("client not found")
		}
		return nil, err
	}

	return &client, nil
}

func (r *ClientRepository) FindByID(ctx context.Context, id uuid.UUID) (*models.Client, error) {
	query := `
		SELECT id, name, email, phone, address, username, password, status, is_active, 
		       last_login, created_at, updated_at, deleted_at
		FROM clients
		WHERE id = $1 AND deleted_at IS NULL
	`

	var client models.Client
	err := r.db.QueryRow(ctx, query, id).Scan(
		&client.ID,
		&client.Name,
		&client.Email,
		&client.Phone,
		&client.Address,
		&client.Username,
		&client.Password,
		&client.Status,
		&client.IsActive,
		&client.LastLogin,
		&client.CreatedAt,
		&client.UpdatedAt,
		&client.DeletedAt,
	)

	if err != nil {
		if errors.Is(err, pgx.ErrNoRows) {
			return nil, errors.New("client not found")
		}
		return nil, err
	}

	return &client, nil
}

func (r *ClientRepository) UpdateLastLogin(ctx context.Context, id uuid.UUID) error {
	now := time.Now()
	query := `
		UPDATE clients
		SET last_login = $1, updated_at = $1
		WHERE id = $2
	`

	_, err := r.db.Exec(ctx, query, now, id)
	return err
}

