import { int, mysqlEnum, mysqlTable, text } from 'drizzle-orm/mysql-core';
import { admin } from './admin.ts';
import { report } from './report.ts';
import type { MySql2Database } from 'drizzle-orm/mysql2';
import { eq } from 'drizzle-orm';

type Database = MySql2Database<{ reportStatus: typeof reportStatus }>;

export const reportStatus = mysqlTable('report_status', {
  status: mysqlEnum('status', ['open', 'closed']),
  notice: text('notice'),
  statement: text('statement'),
  reportId: int('report_id')
    .notNull()
    .unique()
    .references(() => report.id),
  reviewerId: int('reviewer_id').references(() => admin.id)
});

export type GetReportStatusReq = {
  reportId: number;
};

export type EditReportStatusReq = {
  reportId: number;
  status: 'open' | 'closed' | null;
  notice: string | null;
  statement: string | null;
};

export async function getReportStatus(db: Database, values: GetReportStatusReq) {
  const rs = await db.query.reportStatus.findFirst({
    where: eq(reportStatus.reportId, values.reportId)
  });

  return rs ?? null;
}

export async function editReportStatus(db: Database, values: EditReportStatusReq) {
  return db
    .insert(reportStatus)
    .values(values)
    .onDuplicateKeyUpdate({
      set: {
        status: values.status,
        notice: values.notice,
        statement: values.statement
      }
    });
}
