<?php

namespace App\Controllers\Api;

use App\Libraries\AuditLogger;
use App\Libraries\ResponseHelper;
use App\Libraries\UuidHelper;
use App\Models\CommitteeMemberModel;
use App\Models\MemberModel;

class CommitteeController extends BaseApiController
{
    private CommitteeMemberModel $model;

    public function initController(
        \CodeIgniter\HTTP\RequestInterface $request,
        \CodeIgniter\HTTP\ResponseInterface $response,
        \Psr\Log\LoggerInterface $logger
    ): void {
        parent::initController($request, $response, $logger);
        $this->model = $this->scopedModel(new CommitteeMemberModel());
    }

    public function index()
    {
        if ($err = $this->requirePermission('view_committee')) return $err;

        $this->model->where('is_active', 1);
        $result         = $this->model->scopedPaginate($this->getPerPage());
        $result['data'] = array_map([$this, 'format'], $result['data']);

        return ResponseHelper::paginated($result);
    }

    public function create()
    {
        if ($err = $this->requirePermission('manage_committee')) return $err;

        $data = $this->getJson();
        $v    = service('validation');
        $v->setRules([
            'member_uuid' => 'required',
            'role'        => 'required|min_length[2]',
        ]);

        if (!$v->run($data)) {
            return ResponseHelper::validationError($v->getErrors());
        }

        $memberModel = $this->scopedModel(new MemberModel());
        $member      = $memberModel->findByUuid($data['member_uuid']);
        if (!$member) return ResponseHelper::notFound('Member not found');

        $uuid = UuidHelper::generate();
        $this->model->insert([
            'uuid'             => $uuid,
            'church_id'        => $this->churchId(),
            'member_id'        => $member['id'],
            'role'             => $data['role'],
            'responsibilities' => $data['responsibilities'] ?? null,
            'is_active'        => 1,
            'joined_at'        => $data['joined_at'] ?? date('Y-m-d'),
        ]);

        $row = $this->model->findByUuid($uuid);
        AuditLogger::log('committee.created', 'committee_members', $uuid, null, $row);

        return ResponseHelper::created($this->format($row));
    }

    public function update(string $uuid)
    {
        if ($err = $this->requirePermission('manage_committee')) return $err;

        $row = $this->model->findByUuid($uuid);
        if (!$row) return ResponseHelper::notFound();

        $data    = $this->getJson();
        $allowed = ['role', 'responsibilities', 'is_active'];
        $update  = array_intersect_key($data, array_flip($allowed));

        $old = $row;
        $this->model->update($row['id'], $update);
        $new = $this->model->findByUuid($uuid);

        AuditLogger::log('committee.updated', 'committee_members', $uuid, $old, $new);

        return ResponseHelper::success($this->format($new));
    }

    public function delete(string $uuid)
    {
        if ($err = $this->requirePermission('manage_committee')) return $err;

        $row = $this->model->findByUuid($uuid);
        if (!$row) return ResponseHelper::notFound();

        $this->model->delete($row['id']);
        AuditLogger::log('committee.deleted', 'committee_members', $uuid, $row, null);

        return ResponseHelper::success(null);
    }

    private function format(array $r): array
    {
        return [
            'uuid'             => $r['uuid'],
            'member_id'        => $r['member_id'],
            'role'             => $r['role'],
            'responsibilities' => $r['responsibilities'],
            'is_active'        => (bool) $r['is_active'],
            'joined_at'        => $r['joined_at'],
            'created_at'       => $r['created_at'],
        ];
    }
}
