package model

import (
	"crawler/config"
	"crawler/service"
	"database/sql"
)

type MovieSearchModel struct {
	MovieSearch
	MovieListParams
	DailyBoxOfficeParams
	WeeklyBoxOfficeListParams
}

type MovieSearch struct {
	SearchID string
	Params   string
	IDs      string
}

// 영화 목록 검색 변수
type MovieListParams struct {
	CurPage       any `json:"curPage"`
	ItemPerPage   any `json:"itemPerPage"`
	MovieNm       any `json:"movieNm"`
	DirectorNm    any `json:"directorNm"`
	OpenStartDt   any `json:"openStartDt"`
	OpenEndDt     any `json:"openEndDt"`
	PrdtStartYear any `json:"prdtStartYear"`
	PrdtEndYear   any `json:"prdtEndYear"`
	RepNationCd   any `json:"repNationCd"`
	MovieTypeCd   any `json:"movieTypeCd"`
}

// 일별 박스오피스 검색 변수
type DailyBoxOfficeParams struct {
	TargetDt     any `json:"targetDt"`
	ItemPerPage  any `json:"itemPerPage"`
	MultiMovieYn any `json:"multiMovieYn"`
	RepNationCd  any `json:"repNationCd"`
	WideAreaCd   any `json:"wideAreaCd"`
}

// 주간/주말 박스오피스 검색 변수
type WeeklyBoxOfficeListParams struct {
	TargetDt     any `json:"targetDt"`
	WeekGb       any `json:"weekGb"`
	ItemPerPage  any `json:"itemPerPage"`
	MultiMovieYn any `json:"multiMovieYn"`
	RepNationCd  any `json:"repNationCd"`
	WideAreaCd   any `json:"wideAreaCd"`
}

func (this *MovieSearchModel) SelectIDs(params string) (string, error) {
	var (
		db    = service.DB_MOVIEW
		conn  = db.SQLDB
		ids   string
		query = `SELECT ids FROM tb_movie_search WHERE params = ?`
	)

	err := conn.QueryRow(query, params).Scan(&ids)
	if err != nil && err != sql.ErrNoRows {
		db.SetErrorLog(err, query)
		return ids, err
	}

	db.SetGeneralLog(config.GL_ACTION_SELECT, query, "select ids movie search")
	return ids, nil
}

func (this *MovieSearchModel) Insert(row MovieSearch) error {
	var (
		db    = service.DB_MOVIEW
		conn  = db.SQLDB
		query = `
			INSERT INTO tb_movie_search (
				params, ids, created_at
			)
			VALUES 
				(?, ?, NOW())
			ON DUPLICATE KEY UPDATE 
				params = VALUES(params), ids = VALUES(ids), created_at = VALUES(created_at);
		`
	)

	_, err := conn.Exec(query, row.Params, row.IDs)
	if err != nil {
		db.SetErrorLog(err, query)
		return err
	}

	db.SetGeneralLog(config.GL_ACTION_WRITE, query, "insert movie search")
	return nil
}
