import { QueryInterface, DataTypes } from 'sequelize';

export async function up(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.sequelize.query(`DO $$
  BEGIN
    IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'enum_document_category') THEN
      CREATE TYPE enum_document_category AS ENUM ('SUPPORTING','APPROVAL','REFERENCE','FINAL','OTHER','COMPLETION_DOC','ACTIVITY_PHOTO');
    END IF;
  END$$;`);

  await queryInterface.createTable('documents', {
    document_id: { type: DataTypes.UUID, primaryKey: true, defaultValue: DataTypes.UUIDV4 },
    request_id: { type: DataTypes.UUID, allowNull: false, references: { model: 'workflow_requests', key: 'request_id' } },
    uploaded_by: { type: DataTypes.UUID, allowNull: false, references: { model: 'users', key: 'user_id' } },
    file_name: { type: DataTypes.STRING(255), allowNull: false },
    original_file_name: { type: DataTypes.STRING(255), allowNull: false },
    file_type: { type: DataTypes.STRING(100), allowNull: false },
    file_extension: { type: DataTypes.STRING(10), allowNull: false },
    file_size: { type: DataTypes.BIGINT, allowNull: false },
    file_path: { type: DataTypes.STRING(500), allowNull: false },
    storage_url: { type: DataTypes.STRING(500), allowNull: true },
    mime_type: { type: DataTypes.STRING(100), allowNull: false },
    checksum: { type: DataTypes.STRING(64), allowNull: false },
    is_google_doc: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
    google_doc_url: { type: DataTypes.STRING(500), allowNull: true },
    category: { type: 'enum_document_category' as any, allowNull: false, defaultValue: 'OTHER' },
    version: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 1 },
    parent_document_id: { type: DataTypes.UUID, allowNull: true, references: { model: 'documents', key: 'document_id' } },
    is_deleted: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: false },
    download_count: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
    uploaded_at: { type: DataTypes.DATE, allowNull: false, defaultValue: DataTypes.NOW },
  });

  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "documents_request_id" ON "documents" ("request_id");');
  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "documents_uploaded_by" ON "documents" ("uploaded_by");');
  await queryInterface.sequelize.query('CREATE INDEX IF NOT EXISTS "documents_category" ON "documents" ("category");');
}

export async function down(queryInterface: QueryInterface): Promise<void> {
  await queryInterface.dropTable('documents');
  await queryInterface.sequelize.query('DROP TYPE IF EXISTS enum_document_category;');
}


