import {
	index,
	integer,
	jsonb,
	pgTable,
	text,
	timestamp,
	uuid,
} from "drizzle-orm/pg-core";
import { createInsertSchema, createSelectSchema } from "drizzle-zod";
import type { z } from "zod";

export const jobAuditLog = pgTable(
	"job_audit_log",
	{
		id: uuid("id").defaultRandom().primaryKey(),
		jobName: text("job_name"),
		startedAt: timestamp("start_at"),
		finishedAt: timestamp("finished_at", { withTimezone: true }),
		durationMs: integer("duration_ms"),
		status: text("status"), //success | error
		errorMessage: text("error_message"),
		errorStack: text("error_stack"),
		metadata: jsonb("meta_data"),
		createdAt: timestamp("created_at", { withTimezone: true }).defaultNow(),
	},
	(table) => {
		return {
			cleanupIdx: index("idx_job_audit_logs_cleanup").on(
				table.startedAt,
				table.id,
			),
		};
	},
);

export const jobAuditLogSchema = createSelectSchema(jobAuditLog);
export const newJobAuditLogSchema = createInsertSchema(jobAuditLog);

export type JobAuditLog = z.infer<typeof jobAuditLogSchema>;
export type NewJobAuditLog = z.infer<typeof newJobAuditLogSchema>;
