import { BaseSchema } from '@adonisjs/lucid/schema'

export default class extends BaseSchema {
  protected tableName = 'checkin_tasks'

  async up() {
    this.schema.createTable(this.tableName, (table) => {
      table.uuid('id').primary().notNullable().defaultTo(this.raw('gen_random_uuid()'))
      table
        .uuid('organization_id')
        .notNullable()
        .references('id')
        .inTable('organizations')
        .onDelete('CASCADE')
      table
        .uuid('invoice_id')
        .notNullable()
        .references('id')
        .inTable('invoices')
        .onDelete('CASCADE')

      table.timestamp('send_at').notNullable()
      // Token signé HMAC, TTL 24h après émission. Stocké hashé.
      table.string('token_hash', 64).notNullable().unique()
      table
        .enum('status', ['scheduled', 'sent', 'answered', 'expired'], {
          useNative: true,
          enumName: 'checkin_task_status',
        })
        .notNullable()
        .defaultTo('scheduled')
      table.timestamp('sent_at').nullable()
      table.timestamp('answered_at').nullable()
      // Réponse de l'utilisateur via le lien email : 'paid' ou 'still_pending'
      table.string('answer', 20).nullable()

      table.timestamp('created_at').notNullable()
      table.timestamp('updated_at').nullable()

      table.index(['organization_id', 'status'])
      table.index(['invoice_id'])
    })
  }

  async down() {
    this.schema.dropTable(this.tableName)
    this.schema.raw('DROP TYPE IF EXISTS checkin_task_status')
  }
}
