<?php

namespace App\Services;

use App\Enums\TaskStatus;
use App\Repositories\TaskRepository;
use App\Support\IdFormatter;

class TaskService extends BaseService
{
    protected $repository;

    public function __construct()
    {
        $this->repository = new TaskRepository();
    }

    public function getListForTable(?string $orgHex, array $filters = [], int $perPage = 10)
    {
        return $this->repository->paginateByOrganization($orgHex, $filters, $perPage);
    }

    public function getTaskById(string $id, ?string $orgHex)
    {
        return $this->repository->getByIdInOrganization($id, $orgHex);
    }

    public function createTask(array $data, ?string $orgHex)
    {
        $data = $this->prepareCreateData($data, $orgHex, ['assigned_to']);

        $data['created_by'] = IdFormatter::hexToBinary($data['created_by'] ?? auth()->id());
        if (!$data['created_by']) {
            $data['created_by'] = auth()->id();
        }

        if (!isset($data['status'])) {
            $data['status'] = TaskStatus::default()->value;
        }

        return $this->repository->create($data);
    }

    public function updateTask(string $id, array $data, ?string $orgHex)
    {
        $old = $this->repository->getByIdInOrganization($id, $orgHex);
        if (!$old) {
            return false;
        }

        if (isset($data['assigned_to'])) {
            $bin = IdFormatter::hexToBinary($data['assigned_to']);
            if ($bin) {
                $data['assigned_to'] = $bin;
            }
        }

        // Auto-set completed_at khi chuyển status sang 'done'
        if (array_key_exists('status', $data)) {
            $data['completed_at'] = $data['status'] === 'done' ? now() : null;
        }

        return $this->repository->updateInOrganization($id, $data, $orgHex);
    }

    public function updateTaskStatus(string $id, string $status, ?string $completedAt, ?string $orgHex)
    {
        $old = $this->repository->getByIdInOrganization($id, $orgHex);
        if (!$old) {
            return false;
        }

        $data = ['status' => $status];
        if ($status === 'done' && $completedAt) {
            $data['completed_at'] = $completedAt;
        }
        if ($status !== 'done') {
            $data['completed_at'] = null;
        }

        return $this->repository->updateInOrganization($id, $data, $orgHex);
    }

    public function deleteTask(string $id, ?string $orgHex)
    {
        $old = $this->repository->getByIdInOrganization($id, $orgHex);
        if (!$old) {
            return false;
        }

        $deleted = $this->repository->deleteInOrganization($id, $orgHex);

        return $deleted;
    }
}
