<?php

namespace MintyPHP\Module\Helpdesk\Repository;

use MintyPHP\DB;
use MintyPHP\Repository\Support\RepoQuery;

class UpdateRepository
{
    /**
     * @param array<string, mixed> $data
     * @return int|null Inserted ID or null on failure
     */
    public function insert(array $data): ?int
    {
        $result = DB::insert(
            'INSERT INTO helpdesk_updates '
            . '(tenant_id, ticket_no, category_code, debitor_no, debitor_name, domain_no, domain_url, gitea_path, notes, status, created_by) '
            . 'VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
            (string) ($data['tenant_id'] ?? 0),
            (string) ($data['ticket_no'] ?? ''),
            (string) ($data['category_code'] ?? ''),
            (string) ($data['debitor_no'] ?? ''),
            (string) ($data['debitor_name'] ?? ''),
            (string) ($data['domain_no'] ?? ''),
            (string) ($data['domain_url'] ?? ''),
            (string) ($data['gitea_path'] ?? ''),
            $data['notes'] ?? null,
            (string) ($data['status'] ?? 'open'),
            (string) ($data['created_by'] ?? 0)
        );

        if ($result === false) {
            return null;
        }

        return (int) $result;
    }

    public function findByTicketNo(int $tenantId, string $ticketNo): ?array
    {
        if ($ticketNo === '') {
            return null;
        }

        $row = DB::selectOne(
            'SELECT u.*,'
            . ' uc.display_name AS created_by_label'
            . ' FROM helpdesk_updates u'
            . ' LEFT JOIN users uc ON uc.id = u.created_by'
            . ' WHERE u.tenant_id = ? AND u.ticket_no = ? LIMIT 1',
            (string) $tenantId,
            $ticketNo
        );

        return $this->normalizeRow($row);
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function findByDomainNo(int $tenantId, string $domainNo): array
    {
        if ($domainNo === '') {
            return [];
        }

        $rows = DB::select(
            'SELECT u.*,'
            . ' uc.display_name AS created_by_label'
            . ' FROM helpdesk_updates u'
            . ' LEFT JOIN users uc ON uc.id = u.created_by'
            . ' WHERE u.tenant_id = ? AND u.domain_no = ?'
            . ' ORDER BY u.created_at DESC',
            (string) $tenantId,
            $domainNo
        );

        return $this->normalizeRows($rows);
    }

    /**
     * @return list<array<string, mixed>>
     */
    public function findAllByTenant(int $tenantId): array
    {
        $rows = DB::select(
            'SELECT u.ticket_no, u.domain_no, u.domain_url, u.gitea_path, u.notes, u.status,'
            . ' u.category_code, u.debitor_no, u.id'
            . ' FROM helpdesk_updates u'
            . ' WHERE u.tenant_id = ?',
            (string) $tenantId
        );

        return $this->normalizeRows($rows);
    }

    /**
     * @param array<string, mixed> $data
     */
    public function updateAssignment(int $tenantId, int $id, array $data): bool
    {
        $result = DB::update(
            'UPDATE helpdesk_updates SET domain_no = ?, domain_url = ?, gitea_path = ?, notes = ?, status = ?, updated_by = ? WHERE id = ? AND tenant_id = ?',
            (string) ($data['domain_no'] ?? ''),
            (string) ($data['domain_url'] ?? ''),
            (string) ($data['gitea_path'] ?? ''),
            $data['notes'] ?? null,
            (string) ($data['status'] ?? 'assigned'),
            (string) ($data['updated_by'] ?? 0),
            (string) $id,
            (string) $tenantId
        );

        return $result !== false;
    }

    /**
     * @param mixed $rows
     * @return list<array<string, mixed>>
     */
    private function normalizeRows(mixed $rows): array
    {
        $normalized = [];
        if (is_array($rows)) {
            foreach ($rows as $row) {
                $item = $this->normalizeRow($row);
                if ($item !== null) {
                    $normalized[] = $item;
                }
            }
        }

        return $normalized;
    }

    private function normalizeRow(mixed $row): ?array
    {
        if (!is_array($row)) {
            return null;
        }

        $item = [];
        foreach ($row as $key => $value) {
            if (is_array($value)) {
                $item = array_merge($item, $value);
            } else {
                $item[$key] = $value;
            }
        }

        if (!isset($item['id']) && !isset($item['ticket_no'])) {
            return null;
        }

        return $item;
    }
}
