package models

import (
	"context"
	"database/sql"
	"screenmark/screenmark/.gen/haystack/haystack/model"
	. "screenmark/screenmark/.gen/haystack/haystack/table"

	. "github.com/go-jet/jet/v2/postgres"

	"github.com/google/uuid"
)

type NoteModel struct {
	dbPool *sql.DB
}

func (m NoteModel) List(ctx context.Context, userId uuid.UUID) ([]model.Notes, error) {
	listNotesStmt := SELECT(Notes.AllColumns).
		FROM(
			Notes.
				INNER_JOIN(UserNotes, UserNotes.NoteID.EQ(Notes.ID)),
		).
		WHERE(UserNotes.UserID.EQ(UUID(userId)))

	locations := []model.Notes{}

	err := listNotesStmt.QueryContext(ctx, m.dbPool, &locations)
	return locations, err
}

func (m NoteModel) Save(ctx context.Context, userId uuid.UUID, note model.Notes) (model.Notes, error) {
	insertNoteStmt := Notes.
		INSERT(Notes.Name, Notes.Description, Notes.Content).
		VALUES(note.Name, note.Description, note.Content).
		RETURNING(Notes.AllColumns)

	insertedNote := model.Notes{}
	err := insertNoteStmt.QueryContext(ctx, m.dbPool, &insertedNote)
	if err != nil {
		return model.Notes{}, err
	}

	insertUserNoteStmt := UserNotes.
		INSERT(UserNotes.UserID, UserNotes.NoteID).
		VALUES(userId, insertedNote.ID)

	_, err = insertUserNoteStmt.ExecContext(ctx, m.dbPool)

	return insertedNote, err
}

func (m NoteModel) SaveToImage(ctx context.Context, imageId uuid.UUID, noteId uuid.UUID) (model.ImageNotes, error) {
	insertImageNoteStmt := ImageNotes.
		INSERT(ImageNotes.ImageID, ImageNotes.NoteID).
		VALUES(imageId, noteId).
		RETURNING(ImageNotes.AllColumns)

	imageNote := model.ImageNotes{}
	err := insertImageNoteStmt.QueryContext(ctx, m.dbPool, &imageNote)

	return imageNote, err
}

func NewNoteModel(db *sql.DB) NoteModel {
	return NoteModel{dbPool: db}
}
