<?php

namespace App\Models;

use CodeIgniter\Model;

class ExamDraftModel extends Model
{
    protected $table = 'exam_drafts';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $useTimestamps = true;
    protected $createdField = 'created_at';
    protected $updatedField = 'updated_at';
    protected bool $updateOnlyChanged = false;

    /** @var list<string> Stored in `status` column */
    public const STATUSES = [
        'submitted',
        'accepted',
        'review needed',
        'rejected',
        'canceled',
        'under review',
        'legacy',
    ];

    /** @var list<string> Stored in `acceptance_type` when status is finalized */
    public const ACCEPTANCE_TYPES = [
        'as_is',
        'minor_edits',
    ];

    protected $allowedFields = [
        'author_id',
        'class_section_id',
        'semester',
        'school_year',
        'exam_type',
        'draft_title',
        'author_comment',
        'author_file',
        'author_filename',
        'status',
        'acceptance_type',
        'review_revision',
        'reviewer_id',
        'is_legacy',
        'reviewer_comments',
        'reviewed_at',
        'final_file',
        'final_filename',
        'final_pdf_file',
        'version',
        'previous_draft_id',
    ];

    /**
     * Applied on insert/update when validation runs (e.g. $model->insert($data, true)).
     * Uses if_exist so partial updates still validate only keys present in $data.
     */
    protected $validationRules = [
        'status' => 'if_exist|in_list[submitted,accepted,review needed,rejected,canceled,under review,legacy]',
        'acceptance_type' => 'if_exist|permit_empty|in_list[as_is,minor_edits]',
        'author_id' => 'if_exist|is_natural_no_zero',
        'class_section_id' => 'if_exist|is_natural_no_zero',
        'version' => 'if_exist|is_natural_no_zero',
    ];

    protected $validationMessages = [
        'status' => [
            'in_list' => 'Invalid exam draft status.',
        ],
        'acceptance_type' => [
            'in_list' => 'Acceptance must be as_is or minor_edits.',
        ],
    ];

    /**
     * @var array<string, string>
     */
    protected array $casts = [
        'author_id' => 'int',
        'class_section_id' => 'int',
        'reviewer_id' => '?int',
        'review_revision' => 'int',
        'version' => 'int',
        'previous_draft_id' => '?int',
        'is_legacy' => 'boolean',
    ];
}
