<?php

namespace App\Controllers\Api;

use App\Models\SiteModel;

class Sites extends BaseApiController
{
    public function index()
    {
        if ($response = $this->requireAnyApiScope(['sites:read', 'facilities:read'])) {
            return $response;
        }

        $sites = (new SiteModel())
            ->where('organization_id', $this->apiOrganizationId())
            ->orderBy('name', 'ASC')
            ->findAll();

        return $this->respondOk($sites);
    }

    public function create()
    {
        if ($response = $this->requireAnyApiScope(['sites:write', 'facilities:write'])) {
            return $response;
        }

        $payload = $this->payload();
        $data = [
            'organization_id' => $this->apiOrganizationId(),
            'name' => trim((string) ($payload['name'] ?? '')),
            'site_code' => trim((string) ($payload['site_code'] ?? '')),
            'site_type' => trim((string) ($payload['site_type'] ?? 'wind_farm')) ?: 'wind_farm',
            'country_code' => strtoupper(trim((string) ($payload['country_code'] ?? ''))) ?: null,
            'region' => trim((string) ($payload['region'] ?? '')) ?: null,
            'location' => trim((string) ($payload['location'] ?? '')) ?: null,
            'latitude' => $this->nullableDecimal($payload['latitude'] ?? null),
            'longitude' => $this->nullableDecimal($payload['longitude'] ?? null),
            'commissioned_at' => trim((string) ($payload['commissioned_at'] ?? '')) ?: null,
            'status' => trim((string) ($payload['status'] ?? 'active')) ?: 'active',
        ];

        $rules = [
            'organization_id' => 'required|integer',
            'name' => 'required|min_length[3]|max_length[160]',
            'site_code' => 'required|max_length[80]',
            'site_type' => 'required|in_list[wind_farm,site,substation,service_hub]',
            'country_code' => 'permit_empty|exact_length[2]',
            'region' => 'permit_empty|max_length[80]',
            'location' => 'permit_empty|max_length[190]',
            'latitude' => 'permit_empty|decimal',
            'longitude' => 'permit_empty|decimal',
            'commissioned_at' => 'permit_empty|valid_date[Y-m-d]',
            'status' => 'required|in_list[active,inactive,pending,maintenance]',
        ];

        if (! $this->validateData($data, $rules)) {
            return $this->failValidation($this->validator->getErrors());
        }

        $model = new SiteModel();
        $exists = $model
            ->where('organization_id', $data['organization_id'])
            ->where('site_code', $data['site_code'])
            ->first();

        if ($exists) {
            return $this->failValidation([
                'site_code' => 'A site with this code already exists for the active organization.',
            ]);
        }

        $id = $model->insert($data, true);

        return $this->respondOk($model->find($id), 201);
    }

    private function nullableDecimal($value): ?string
    {
        $value = trim((string) $value);

        return $value === '' ? null : $value;
    }
}
