package repository

import (
	"context"
	"database/sql"
	"errors"
	"fmt"
	"github.com/google/uuid"
	_ "github.com/mattn/go-sqlite3" // Import the SQLite3 driver
	"go-nkode/config"
	"go-nkode/internal/entities"
	"go-nkode/internal/models"
	"go-nkode/internal/security"
	"go-nkode/internal/sqlc"
	"go-nkode/internal/utils"
	"log"
)

type SqliteRepository struct {
	Queue *sqlc.Queue
	ctx   context.Context
}

func NewSqliteRepository(ctx context.Context, queue *sqlc.Queue) SqliteRepository {
	return SqliteRepository{
		Queue: queue,
		ctx:   ctx,
	}
}

func (d *SqliteRepository) CreateCustomer(c entities.Customer) error {
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.CreateCustomerParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected CreateCustomerParams")
		}
		return nil, q.CreateCustomer(ctx, params)
	}

	_, err := d.Queue.EnqueueWriteTx(queryFunc, c.ToSqlcCreateCustomerParams())
	return err
}

func (d *SqliteRepository) WriteNewUser(u entities.User) error {
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.CreateUserParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected CreateUserParams")
		}
		return nil, q.CreateUser(ctx, params)
	}
	// Use the wrapped function in EnqueueWriteTx
	renew := 0
	if u.Renew {
		renew = 1
	}
	// Map entities.User to CreateUserParams
	params := sqlc.CreateUserParams{
		ID:               uuid.UUID(u.Id).String(),
		Email:            string(u.Email),
		Renew:            int64(renew),
		RefreshToken:     sql.NullString{String: u.RefreshToken, Valid: u.RefreshToken != ""},
		CustomerID:       uuid.UUID(u.CustomerId).String(),
		Code:             u.EncipheredPasscode.Code,
		Mask:             u.EncipheredPasscode.Mask,
		AttributesPerKey: int64(u.Kp.AttrsPerKey),
		NumberOfKeys:     int64(u.Kp.NumbOfKeys),
		AlphaKey:         security.Uint64ArrToByteArr(u.CipherKeys.AlphaKey),
		SetKey:           security.Uint64ArrToByteArr(u.CipherKeys.SetKey),
		PassKey:          security.Uint64ArrToByteArr(u.CipherKeys.PassKey),
		MaskKey:          security.Uint64ArrToByteArr(u.CipherKeys.MaskKey),
		Salt:             u.CipherKeys.Salt,
		MaxNkodeLen:      int64(u.CipherKeys.MaxNKodeLen),
		IdxInterface:     security.IntArrToByteArr(u.Interface.IdxInterface),
		SvgIDInterface:   security.IntArrToByteArr(u.Interface.SvgId),
		CreatedAt:        sql.NullString{String: utils.TimeStamp(), Valid: true},
	}
	_, err := d.Queue.EnqueueWriteTx(queryFunc, params)
	return err
}

func (d *SqliteRepository) UpdateUserNKode(u entities.User) error {
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.UpdateUserParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected UpdateUserParams")
		}
		return nil, q.UpdateUser(ctx, params)
	}
	// Use the wrapped function in EnqueueWriteTx
	renew := 0
	if u.Renew {
		renew = 1
	}
	params := sqlc.UpdateUserParams{
		Email:            string(u.Email),
		Renew:            int64(renew),
		RefreshToken:     sql.NullString{String: u.RefreshToken, Valid: u.RefreshToken != ""},
		CustomerID:       uuid.UUID(u.CustomerId).String(),
		Code:             u.EncipheredPasscode.Code,
		Mask:             u.EncipheredPasscode.Mask,
		AttributesPerKey: int64(u.Kp.AttrsPerKey),
		NumberOfKeys:     int64(u.Kp.NumbOfKeys),
		AlphaKey:         security.Uint64ArrToByteArr(u.CipherKeys.AlphaKey),
		SetKey:           security.Uint64ArrToByteArr(u.CipherKeys.SetKey),
		PassKey:          security.Uint64ArrToByteArr(u.CipherKeys.PassKey),
		MaskKey:          security.Uint64ArrToByteArr(u.CipherKeys.MaskKey),
		Salt:             u.CipherKeys.Salt,
		MaxNkodeLen:      int64(u.CipherKeys.MaxNKodeLen),
		IdxInterface:     security.IntArrToByteArr(u.Interface.IdxInterface),
		SvgIDInterface:   security.IntArrToByteArr(u.Interface.SvgId),
	}
	_, err := d.Queue.EnqueueWriteTx(queryFunc, params)
	return err
}

func (d *SqliteRepository) UpdateUserInterface(id models.UserId, ui entities.UserInterface) error {
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.UpdateUserInterfaceParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected UpdateUserInterfaceParams")
		}
		return nil, q.UpdateUserInterface(ctx, params)
	}
	params := sqlc.UpdateUserInterfaceParams{
		IdxInterface: security.IntArrToByteArr(ui.IdxInterface),
		LastLogin:    utils.TimeStamp(),
		ID:           uuid.UUID(id).String(),
	}
	_, err := d.Queue.EnqueueWriteTx(queryFunc, params)
	return err
}

func (d *SqliteRepository) UpdateUserRefreshToken(id models.UserId, refreshToken string) error {
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.UpdateUserRefreshTokenParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected UpdateUserRefreshToken")
		}
		return nil, q.UpdateUserRefreshToken(ctx, params)
	}
	params := sqlc.UpdateUserRefreshTokenParams{
		RefreshToken: sql.NullString{
			String: refreshToken,
			Valid:  true,
		},
		ID: uuid.UUID(id).String(),
	}
	_, err := d.Queue.EnqueueWriteTx(queryFunc, params)
	return err
}

func (d *SqliteRepository) RenewCustomer(renewParams sqlc.RenewCustomerParams) error {
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.RenewCustomerParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected RenewCustomerParams")
		}
		return nil, q.RenewCustomer(ctx, params)
	}
	_, err := d.Queue.EnqueueWriteTx(queryFunc, renewParams)
	return err
}

func (d *SqliteRepository) Renew(id models.CustomerID) error {
	setXor, attrXor, err := d.renewCustomer(id)
	if err != nil {
		return err
	}
	customerId := models.CustomerIdToString(id)
	userRenewRows, err := d.Queue.Queries.GetUserRenew(d.ctx, customerId)
	if err != nil {
		return err
	}
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.RenewUserParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected RenewUserParams")
		}
		return nil, q.RenewUser(ctx, params)
	}
	for _, row := range userRenewRows {
		user := entities.User{
			Id:                 models.UserIdFromString(row.ID),
			CustomerId:         models.CustomerID{},
			Email:              "",
			EncipheredPasscode: models.EncipheredNKode{},
			Kp: entities.KeypadDimension{
				AttrsPerKey: int(row.AttributesPerKey),
				NumbOfKeys:  int(row.NumberOfKeys),
			},
			CipherKeys: entities.UserCipherKeys{
				AlphaKey: security.ByteArrToUint64Arr(row.AlphaKey),
				SetKey:   security.ByteArrToUint64Arr(row.SetKey),
			},
			Interface: entities.UserInterface{},
			Renew:     false,
		}
		if err = user.RenewKeys(setXor, attrXor); err != nil {
			return err
		}
		params := sqlc.RenewUserParams{
			AlphaKey: security.Uint64ArrToByteArr(user.CipherKeys.AlphaKey),
			SetKey:   security.Uint64ArrToByteArr(user.CipherKeys.SetKey),
			Renew:    1,
			ID:       uuid.UUID(user.Id).String(),
		}
		if _, err = d.Queue.EnqueueWriteTx(queryFunc, params); err != nil {
			return err
		}
	}
	return nil
}

func (d *SqliteRepository) renewCustomer(id models.CustomerID) ([]uint64, []uint64, error) {
	customer, err := d.GetCustomer(id)
	if err != nil {
		return nil, nil, err
	}
	setXor, attrXor, err := customer.RenewKeys()
	if err != nil {
		return nil, nil, err
	}
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.RenewCustomerParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected RenewCustomerParams")
		}
		return nil, q.RenewCustomer(ctx, params)
	}
	params := sqlc.RenewCustomerParams{
		AttributeValues: security.Uint64ArrToByteArr(customer.Attributes.AttrVals),
		SetValues:       security.Uint64ArrToByteArr(customer.Attributes.SetVals),
		ID:              uuid.UUID(customer.ID).String(),
	}
	if _, err = d.Queue.EnqueueWriteTx(queryFunc, params); err != nil {
		return nil, nil, err
	}
	return setXor, attrXor, nil
}

func (d *SqliteRepository) RefreshUserPasscode(user entities.User, passcodeIdx []int, customerAttr entities.CustomerAttributes) error {
	if err := user.RefreshPasscode(passcodeIdx, customerAttr); err != nil {
		return err
	}
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(sqlc.RefreshUserPasscodeParams)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected RefreshUserPasscodeParams")
		}
		return nil, q.RefreshUserPasscode(ctx, params)
	}
	params := sqlc.RefreshUserPasscodeParams{
		Renew:    0,
		Code:     user.EncipheredPasscode.Code,
		Mask:     user.EncipheredPasscode.Mask,
		AlphaKey: security.Uint64ArrToByteArr(user.CipherKeys.AlphaKey),
		SetKey:   security.Uint64ArrToByteArr(user.CipherKeys.SetKey),
		PassKey:  security.Uint64ArrToByteArr(user.CipherKeys.PassKey),
		MaskKey:  security.Uint64ArrToByteArr(user.CipherKeys.MaskKey),
		Salt:     user.CipherKeys.Salt,
		ID:       uuid.UUID(user.Id).String(),
	}
	_, err := d.Queue.EnqueueWriteTx(queryFunc, params)
	return err
}

func (d *SqliteRepository) GetCustomer(id models.CustomerID) (*entities.Customer, error) {
	customer, err := d.Queue.Queries.GetCustomer(d.ctx, uuid.UUID(id).String())
	if err != nil {
		return nil, err
	}
	return &entities.Customer{
		ID: id,
		NKodePolicy: models.NKodePolicy{
			MaxNkodeLen:        int(customer.MaxNkodeLen),
			MinNkodeLen:        int(customer.MinNkodeLen),
			DistinctSets:       int(customer.DistinctSets),
			DistinctAttributes: int(customer.DistinctAttributes),
			LockOut:            int(customer.LockOut),
			Expiration:         int(customer.Expiration),
		},
		Attributes: entities.NewCustomerAttributesFromBytes(customer.AttributeValues, customer.SetValues),
	}, nil
}

func (d *SqliteRepository) GetUser(email models.UserEmail, customerId models.CustomerID) (*entities.User, error) {
	userRow, err := d.Queue.Queries.GetUser(d.ctx, sqlc.GetUserParams{
		Email:      string(email),
		CustomerID: uuid.UUID(customerId).String(),
	})
	if err != nil {
		if errors.Is(err, sql.ErrNoRows) {
			return nil, nil
		}
		return nil, fmt.Errorf("failed to get user: %w", err)
	}
	kp := entities.KeypadDimension{
		AttrsPerKey: int(userRow.AttributesPerKey),
		NumbOfKeys:  int(userRow.NumberOfKeys),
	}
	renew := false
	if userRow.Renew == 1 {
		renew = true
	}
	user := entities.User{
		Id:         models.UserIdFromString(userRow.ID),
		CustomerId: customerId,
		Email:      email,
		EncipheredPasscode: models.EncipheredNKode{
			Code: userRow.Code,
			Mask: userRow.Mask,
		},
		Kp: kp,
		CipherKeys: entities.UserCipherKeys{
			AlphaKey:    security.ByteArrToUint64Arr(userRow.AlphaKey),
			SetKey:      security.ByteArrToUint64Arr(userRow.SetKey),
			PassKey:     security.ByteArrToUint64Arr(userRow.PassKey),
			MaskKey:     security.ByteArrToUint64Arr(userRow.MaskKey),
			Salt:        userRow.Salt,
			MaxNKodeLen: int(userRow.MaxNkodeLen),
			Kp:          &kp,
		},
		Interface: entities.UserInterface{
			IdxInterface: security.ByteArrToIntArr(userRow.IdxInterface),
			SvgId:        security.ByteArrToIntArr(userRow.SvgIDInterface),
			Kp:           &kp,
		},
		Renew:        renew,
		RefreshToken: userRow.RefreshToken.String,
	}
	return &user, nil
}

func (d *SqliteRepository) RandomSvgInterface(kp entities.KeypadDimension) ([]string, error) {
	ids, err := d.getRandomIds(kp.TotalAttrs())
	if err != nil {
		return nil, err
	}
	return d.getSvgsById(ids)
}

func (d *SqliteRepository) RandomSvgIdxInterface(kp entities.KeypadDimension) (models.SvgIdInterface, error) {
	return d.getRandomIds(kp.TotalAttrs())
}

func (d *SqliteRepository) GetSvgStringInterface(idxs models.SvgIdInterface) ([]string, error) {
	return d.getSvgsById(idxs)
}

func (d *SqliteRepository) AddSVGIcon(svgStr string) (int64, error) {
	queryFunc := func(q *sqlc.Queries, ctx context.Context, args any) (any, error) {
		params, ok := args.(string)
		if !ok {
			return nil, fmt.Errorf("invalid argument type: expected string")
		}
		return q.AddSVGIcon(ctx, params)
	}
	svgID, err := d.Queue.EnqueueWriteTx(queryFunc, svgStr)
	if err != nil {
		return -1, err
	}
	svgIDInt64, ok := svgID.(int64)
	if !ok {
		return -1, errors.New("svgID in DB isn't int64")
	}
	return svgIDInt64, nil
}

func (d *SqliteRepository) getSvgsById(ids []int) ([]string, error) {
	svgs := make([]string, len(ids))
	for idx, id := range ids {
		svg, err := d.Queue.Queries.GetSvgId(d.ctx, int64(id))
		if err != nil {
			return nil, err
		}
		svgs[idx] = svg
	}
	return svgs, nil
}

func (d *SqliteRepository) getRandomIds(count int) ([]int, error) {
	tx, err := d.Queue.Db.Begin()
	if err != nil {
		log.Print(err)
		return nil, config.ErrSqliteTx
	}
	rows, err := tx.Query("SELECT COUNT(*) as count FROM svg_icon;")
	if err != nil {
		log.Print(err)
		return nil, config.ErrSqliteTx
	}
	var tableLen int
	if !rows.Next() {
		return nil, config.ErrEmptySvgTable
	}

	if err = rows.Scan(&tableLen); err != nil {
		log.Print(err)
		return nil, config.ErrSqliteTx
	}
	perm, err := security.RandomPermutation(tableLen)

	if err != nil {
		return nil, err
	}

	for idx := range perm {
		perm[idx] += 1
	}

	if err = tx.Commit(); err != nil {
		log.Print(err)
		return nil, config.ErrSqliteTx
	}

	return perm[:count], nil
}
