<?php

namespace App\Database\Migrations;

use CodeIgniter\Database\Migration;

class AddReviewFieldsToScoreComments extends Migration
{
    public function up()
    {
        if (!$this->db->tableExists('score_comments')) {
            return;
        }

        $fields = $this->db->getFieldNames('score_comments');

        if (!in_array('comment_review', $fields, true)) {
            $this->forge->addColumn('score_comments', [
                'comment_review' => [
                    'type' => 'TEXT',
                    'null' => true,
                    'after' => 'comment',
                ],
            ]);
        }

        if (!in_array('reviewed_by', $fields, true)) {
            $this->forge->addColumn('score_comments', [
                'reviewed_by' => [
                    'type' => 'INT',
                    'constraint' => 11,
                    'unsigned' => true,
                    'null' => true,
                    'after' => 'comment_review',
                ],
            ]);
        }

        // Allow comments to be nullable so reviewers can attach feedback without a comment body
        if (in_array('comment', $fields, true)) {
            try {
                $this->forge->modifyColumn('score_comments', [
                    'comment' => [
                        'type' => 'TEXT',
                        'null' => true,
                    ],
                ]);
            } catch (\Throwable $e) {
                // Best effort only
            }
        }
    }

    public function down()
    {
        if (!$this->db->tableExists('score_comments')) {
            return;
        }

        try {
            $this->forge->modifyColumn('score_comments', [
                'comment' => [
                    'type' => 'TEXT',
                    'null' => false,
                ],
            ]);
        } catch (\Throwable $e) {
            // Ignore rollback errors
        }

        try {
            $this->forge->dropColumn('score_comments', 'reviewed_by');
        } catch (\Throwable $e) {
            // Ignore rollback errors
        }

        try {
            $this->forge->dropColumn('score_comments', 'comment_review');
        } catch (\Throwable $e) {
            // Ignore rollback errors
        }
    }
}
