package permissions

import (
	"bssapp-backend/queries"
	"database/sql"
	"log"
)

type RoleDepartmentPermissionRepo struct {
	db *sql.DB
}

func NewRoleDepartmentPermissionRepo(db *sql.DB) *RoleDepartmentPermissionRepo {
	return &RoleDepartmentPermissionRepo{db: db}
}

/* ======================================================
   GET
====================================================== */

func (r *RoleDepartmentPermissionRepo) Get(
	roleID int,
	deptCode string,
) ([]RoleDepartmentPermission, error) {

	rows, err := r.db.Query(
		queries.GetRoleDepartmentPermissions,
		roleID,
		deptCode,
	)

	if err != nil {
		return nil, err
	}
	defer rows.Close()

	var list []RoleDepartmentPermission

	for rows.Next() {

		var p RoleDepartmentPermission

		if err := rows.Scan(
			&p.Module,
			&p.Action,
			&p.Allowed,
		); err != nil {
			return nil, err
		}

		p.RoleID = roleID
		p.DepartmentCode = deptCode
		p.Source = "role_department"

		list = append(list, p)
	}

	return list, nil
}

/* ======================================================
   SAVE
====================================================== */

func (r *RoleDepartmentPermissionRepo) Save(
	roleID int,
	deptCode string,
	list []RoleDepartmentPermission,
) error {

	tx, err := r.db.Begin()
	if err != nil {
		return err
	}
	defer tx.Rollback()

	stmt, err := tx.Prepare(
		queries.UpsertRoleDepartmentPermission,
	)
	if err != nil {
		return err
	}
	defer stmt.Close()

	for _, p := range list {

		if p.Module == "" {
			log.Printf(
				"⚠️ SKIP EMPTY MODULE role=%v dept=%v action=%v",
				roleID,
				deptCode,
				p.Action,
			)
			continue
		}

		_, err := stmt.Exec(
			roleID,
			deptCode,
			p.Module,
			p.Action,
			p.Allowed,
		)

		// 🔴🔴🔴 KRİTİK DEBUG LOG
		if err != nil {

			log.Printf(
				"❌ UPSERT FAIL role=%v dept=%v module=%v action=%v allowed=%v err=%v",
				roleID,
				deptCode,
				p.Module,
				p.Action,
				p.Allowed,
				err,
			)

			return err
		}
	}

	return tx.Commit()
}
