import {
  Sequelize,
  DataTypes,
  Model,
  InferAttributes,
  InferCreationAttributes,
  CreationOptional,
} from "sequelize";
import type { CandidateStatus } from "@/types";
import {
  decryptSensitiveUrl,
  encryptSensitiveUrl,
} from "@/lib/utils/sensitive-url-crypto";

export class Candidate extends Model<
  InferAttributes<Candidate>,
  InferCreationAttributes<Candidate>
> {
  declare id: CreationOptional<string>;
  declare electionPositionId: string;
  declare name: string;
  declare photoUrl: string | null;
  declare biography: string | null;
  declare resumeUrl: string | null;
  declare goalsStatement: string | null;
  declare conflictOfInterestDisclosure: string | null;
  declare status: CandidateStatus;
  declare position: CreationOptional<number>;
  declare createdAt: CreationOptional<Date>;
  declare updatedAt: CreationOptional<Date>;
}

export function initCandidateModel(sequelize: Sequelize) {
  Candidate.init(
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },
      electionPositionId: { type: DataTypes.UUID, allowNull: false },
      name: { type: DataTypes.STRING(255), allowNull: false },
      photoUrl: { type: DataTypes.STRING(512), allowNull: true },
      biography: { type: DataTypes.TEXT, allowNull: true },
      resumeUrl: {
        type: DataTypes.STRING(1024),
        allowNull: true,
        get() {
          const raw = this.getDataValue("resumeUrl");
          try {
            return decryptSensitiveUrl(raw);
          } catch {
            return raw;
          }
        },
        set(value: string | null) {
          this.setDataValue("resumeUrl", encryptSensitiveUrl(value));
        },
      },
      goalsStatement: { type: DataTypes.TEXT, allowNull: true },
      conflictOfInterestDisclosure: { type: DataTypes.TEXT, allowNull: true },
      status: {
        type: DataTypes.ENUM("pending", "approved", "withdrawn"),
        allowNull: false,
        defaultValue: "pending",
      },
      position: {
        type: DataTypes.INTEGER,
        allowNull: false,
        defaultValue: 0,
      },
      createdAt: DataTypes.DATE,
      updatedAt: DataTypes.DATE,
    },
    { sequelize, modelName: "Candidate", tableName: "Candidates" }
  );
  return Candidate;
}
