import { db } from '../db/client.js';
export {
  DEFAULT_DAILY_CREATE_TIME,
  ensureDailyWorklogFile,
  getKstNowParts,
  isValidDailyCreateTime,
  isWorklogCreationDue,
  normalizeDailyCreateTime,
  renderWorklogTemplate,
} from './worklog-automation-utils.js';
import { DEFAULT_DAILY_CREATE_TIME, normalizeDailyCreateTime } from './worklog-automation-utils.js';

export const WORKLOG_AUTOMATION_RUN_TABLE = 'worklog_automation_runs';

async function ensureWorklogAutomationRunTable() {
  const hasTable = await db.schema.hasTable(WORKLOG_AUTOMATION_RUN_TABLE);

  if (!hasTable) {
    await db.schema.createTable(WORKLOG_AUTOMATION_RUN_TABLE, (table) => {
      table.increments('id').primary();
      table.string('run_date', 10).notNullable().unique();
      table.string('scheduled_time', 5).notNullable();
      table.string('worklog_path').notNullable();
      table.timestamp('executed_at', { useTz: true }).notNullable().defaultTo(db.fn.now());
    });
    return;
  }

  const requiredColumns: Array<[string, (table: any) => void]> = [
    ['run_date', (table) => table.string('run_date', 10).notNullable().unique()],
    ['scheduled_time', (table) => table.string('scheduled_time', 5).notNullable().defaultTo(DEFAULT_DAILY_CREATE_TIME)],
    ['worklog_path', (table) => table.string('worklog_path').notNullable().defaultTo('')],
    ['executed_at', (table) => table.timestamp('executed_at', { useTz: true }).notNullable().defaultTo(db.fn.now())],
  ];

  for (const [columnName, createColumn] of requiredColumns) {
    const hasColumn = await db.schema.hasColumn(WORKLOG_AUTOMATION_RUN_TABLE, columnName);
    if (!hasColumn) {
      await db.schema.alterTable(WORKLOG_AUTOMATION_RUN_TABLE, (table) => {
        createColumn(table);
      });
    }
  }
}

export async function hasWorklogAutomationRunForDate(runDate: string) {
  await ensureWorklogAutomationRunTable();
  const row = await db(WORKLOG_AUTOMATION_RUN_TABLE).where({ run_date: runDate }).first();
  return Boolean(row);
}

export async function markWorklogAutomationRun(args: {
  runDate: string;
  scheduledTime: string;
  worklogPath: string;
}) {
  await ensureWorklogAutomationRunTable();

  const existing = await db(WORKLOG_AUTOMATION_RUN_TABLE).where({ run_date: args.runDate }).first();
  if (existing) {
    await db(WORKLOG_AUTOMATION_RUN_TABLE)
      .where({ run_date: args.runDate })
      .update({
        scheduled_time: args.scheduledTime,
        worklog_path: args.worklogPath,
        executed_at: db.fn.now(),
      });
    return;
  }

  await db(WORKLOG_AUTOMATION_RUN_TABLE).insert({
    run_date: args.runDate,
    scheduled_time: args.scheduledTime,
    worklog_path: args.worklogPath,
    executed_at: db.fn.now(),
  });
}
