<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class CreateInspectionsTable extends Migration
{
    public function up()
    {
        $this->forge->addField([
            'id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'auto_increment' => true],
            'folio' => ['type' => 'VARCHAR', 'constraint' => 40, 'null' => true],
            'template_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'client_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true],
            'sistema' => ['type' => 'VARCHAR', 'constraint' => 200, 'null' => true],
            'atencion' => ['type' => 'VARCHAR', 'constraint' => 200, 'null' => true],
            'servicio' => ['type' => 'VARCHAR', 'constraint' => 200, 'null' => true],
            'contrato' => ['type' => 'VARCHAR', 'constraint' => 80, 'null' => true],
            'inspector_user_id' => ['type' => 'INT', 'constraint' => 11, 'unsigned' => true, 'null' => true],
            'fecha' => ['type' => 'DATE', 'null' => true],
            'status' => [
                'type' => "ENUM('draft','in_progress','completed','signed')",
                'default' => 'draft',
            ],
            'observaciones' => ['type' => 'TEXT', 'null' => true],
            'started_at' => ['type' => 'DATETIME', 'null' => true],
            'completed_at' => ['type' => 'DATETIME', 'null' => true],
            'signed_at' => ['type' => 'DATETIME', 'null' => true],
            'verify_token' => ['type' => 'CHAR', 'constraint' => 32, 'null' => true],
            'autosave_json' => ['type' => 'LONGTEXT', 'null' => true],
            'autosave_updated_at' => ['type' => 'DATETIME', 'null' => true],
            'created_at' => ['type' => 'DATETIME', 'null' => true],
            'updated_at' => ['type' => 'DATETIME', 'null' => true],
        ]);
        $this->forge->addKey('id', true);
        $this->forge->addUniqueKey('folio');
        $this->forge->addUniqueKey('verify_token');
        $this->forge->addKey('template_id');
        $this->forge->addKey('client_id');
        $this->forge->addKey('status');
        $this->forge->addForeignKey('template_id', 'inspection_templates', 'id', 'RESTRICT', 'CASCADE');
        $this->forge->addForeignKey('client_id', 'clients', 'id', 'RESTRICT', 'CASCADE');
        $this->forge->addForeignKey('inspector_user_id', 'users', 'id', 'SET NULL', 'CASCADE');
        $this->forge->createTable('inspections');
    }

    public function down()
    {
        $this->forge->dropTable('inspections', true);
    }
}
