/*
 * Copyright 2026 Oleg Borodin <onborodin@gmail.com>
 */
package maindb

import (
	"context"

	"mstore/pkg/descr"
)

func (db *Database) InsertFile(ctx context.Context, file *descr.File) error {
	var err error
	request := `INSERT INTO files(id, collection, name, type, checksum, size,
                        created_at, updated_at, created_by, updated_by, helm_hash, helm_meta)
                        VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`
	_, err = db.db.Exec(request, file.ID, file.Collection, file.Name, file.Type, file.Checksum, file.Size,
		file.CreatedAt, file.UpdatedAt, file.CreatedBy, file.UpdatedBy,
		file.HelmHash, file.HelmMeta)
	if err != nil {
		return err
	}
	return err
}

func (db *Database) UpdateFileByID(ctx context.Context, fileID string, file *descr.File) error {
	var err error
	request := `UPDATE files SET id = $1, collection = $2, name = $3, type = $4, checksum = $5,
                          size = $6, updated_at = $7, created_by = $8, updated_by = $9,
                          helm_hash = $10, helm_meta = $11
                          WHERE id = $12`
	_, err = db.db.Exec(request, file.ID, file.Collection, file.Name, file.Type, file.Checksum,
		file.Size, file.UpdatedAt, file.CreatedBy, file.UpdatedBy,
		file.HelmHash, file.HelmMeta, fileID)
	if err != nil {
		return err
	}
	return err
}

func (db *Database) ListFilesByCollection(ctx context.Context, collection string) ([]descr.File, error) {
	var err error
	request := `SELECT * FROM files WHERE collection = $1 ORDER BY collection, name`
	res := make([]descr.File, 0)
	err = db.db.Select(&res, request, collection)
	if err != nil {
		return res, err
	}
	return res, err
}

func (db *Database) ListAllFiles(ctx context.Context) ([]descr.File, error) {
	var err error
	request := `SELECT * FROM files ORDER BY collection, name`
	res := make([]descr.File, 0)
	err = db.db.Select(&res, request)
	if err != nil {
		return res, err
	}
	return res, err
}

func (db *Database) GetFileByCollectionName(ctx context.Context, collection, name string) (bool, *descr.File, error) {
	var err error
	var res *descr.File
	var exists bool
	request := `SELECT * FROM files WHERE collection = $1 AND name = $2 LIMIT 1`
	dbRes := make([]descr.File, 0)
	err = db.db.Select(&dbRes, request, collection, name)
	if err != nil {
		return exists, res, err
	}

	if len(dbRes) == 0 {
		return false, res, err
	}
	exists = true
	res = &dbRes[0]
	return exists, res, err
}

func (db *Database) DeleteFileByCollectionName(ctx context.Context, collection, name string) error {
	var err error
	request := `DELETE FROM files WHERE collection = $1 AND name = $2`
	_, err = db.db.Exec(request, collection, name)
	if err != nil {
		return err
	}
	return err
}
