// Code generated by fkit v3.11.0. DO NOT EDIT.
//
// Source: schema/employee/contract.fkit
// Regenerate with: go run ./tools/fkitgen ./schema/employee

package employee

import (
	"context"
	"database/sql"
	"time"
)

// ContractRow is the generated row type for table contract.
type ContractRow struct {
	ID              string
	EmployeeID      string
	Kind            string
	Currency        string
	RateCents       int64
	PeriodRateCents int64
	StartsOn        time.Time
	EndsOn          time.Time
	CreatedAt       time.Time
	UpdatedAt       time.Time
}

// ContractCreateRequest is the generated create payload for table contract.
type ContractCreateRequest struct {
	EmployeeID      string    `json:"employeeId"`
	Kind            string    `json:"kind"`
	Currency        string    `json:"currency"`
	RateCents       int64     `json:"rateCents"`
	PeriodRateCents int64     `json:"periodRateCents"`
	StartsOn        time.Time `json:"startsOn"`
}

// CreateContract inserts one contract row.
func CreateContract(ctx context.Context, db *sql.DB, req ContractCreateRequest) (ContractRow, error) {
	const q = `INSERT INTO contract (employee_id, kind, currency, rate_cents, period_rate_cents, starts_on)
	           VALUES ($1, $2, $3, $4, $5, $6) RETURNING *`
	return scanContract(db.QueryRowContext(ctx, q, req.EmployeeID, req.Kind, req.Currency,
		req.RateCents, req.PeriodRateCents, req.StartsOn))
}

// GetContract selects one contract row by primary key.
func GetContract(ctx context.Context, db *sql.DB, id string) (ContractRow, error) {
	const q = `SELECT * FROM contract WHERE id = $1`
	return scanContract(db.QueryRowContext(ctx, q, id))
}

// DeleteContract removes one contract row.
func DeleteContract(ctx context.Context, db *sql.DB, id string) error {
	const q = `DELETE FROM contract WHERE id = $1`
	_, err := db.ExecContext(ctx, q, id)
	return err
}

// ListContractsForEmployee selects contract rows for one employee.
func ListContractsForEmployee(ctx context.Context, db *sql.DB, employeeID string) ([]ContractRow, error) {
	const q = `SELECT * FROM contract WHERE employee_id = $1 ORDER BY starts_on DESC`
	rows, err := db.QueryContext(ctx, q, employeeID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var out []ContractRow
	for rows.Next() {
		var r ContractRow
		if err := rows.Scan(&r.ID, &r.EmployeeID, &r.Kind, &r.Currency, &r.RateCents,
			&r.PeriodRateCents, &r.StartsOn, &r.EndsOn, &r.CreatedAt, &r.UpdatedAt); err != nil {
			return nil, err
		}
		out = append(out, r)
	}
	return out, rows.Err()
}

func scanContract(row *sql.Row) (ContractRow, error) {
	var r ContractRow
	err := row.Scan(&r.ID, &r.EmployeeID, &r.Kind, &r.Currency, &r.RateCents,
		&r.PeriodRateCents, &r.StartsOn, &r.EndsOn, &r.CreatedAt, &r.UpdatedAt)
	return r, err
}
