<?php

namespace Modules\Contracts\Services;

use App\Models\ActivityLogModel;
use App\Models\CompanyModel;
use App\Models\CustomerSiteModel;

class SiteService
{
    protected CustomerSiteModel $sites;
    protected CompanyModel $companies;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->sites     = new CustomerSiteModel();
        $this->companies = new CompanyModel();
        $this->activity  = new ActivityLogModel();
    }

    public function create(array $input, ?int $actingUserId): array
    {
        $code = strtoupper(trim($input['code'] ?? ''));
        if ($this->sites->isCodeTaken($code)) {
            return ['success' => false, 'errors' => ['code' => 'That site code is already in use.']];
        }

        $data = $this->mapInput($input);
        $data['code']       = $code;
        $data['created_by'] = $actingUserId;
        $data['updated_by'] = $actingUserId;

        if (! $this->sites->insert($data, true)) {
            return ['success' => false, 'errors' => $this->sites->errors()];
        }

        $id = $this->sites->getInsertID();
        $this->activity->log('customer_sites', 'created', $actingUserId, "Created site #{$id} ({$data['name']})", (string) $id);

        return ['success' => true, 'id' => $id];
    }

    public function update(int $id, array $input, ?int $actingUserId): array
    {
        $site = $this->sites->find($id);
        if (! $site) {
            return ['success' => false, 'errors' => ['id' => 'Site not found.']];
        }

        $code = strtoupper(trim($input['code'] ?? ''));
        if ($this->sites->isCodeTaken($code, $id)) {
            return ['success' => false, 'errors' => ['code' => 'That site code is already in use.']];
        }

        $data = $this->mapInput($input);
        $data['code']       = $code;
        $data['updated_by'] = $actingUserId;

        if (! $this->sites->update($id, $data)) {
            return ['success' => false, 'errors' => $this->sites->errors()];
        }

        $this->activity->log('customer_sites', 'updated', $actingUserId, "Updated site #{$id}", (string) $id);

        return ['success' => true];
    }

    public function activate(int $id, ?int $actingUserId): void
    {
        $this->sites->update($id, ['status' => 'active', 'updated_by' => $actingUserId]);
        $this->activity->log('customer_sites', 'activated', $actingUserId, "Activated site #{$id}", (string) $id);
    }

    public function deactivate(int $id, ?int $actingUserId): void
    {
        $this->sites->update($id, ['status' => 'inactive', 'updated_by' => $actingUserId]);
        $this->activity->log('customer_sites', 'deactivated', $actingUserId, "Deactivated site #{$id}", (string) $id);
    }

    public function delete(int $id, ?int $actingUserId): array
    {
        $site = $this->sites->find($id);
        if (! $site) {
            return ['success' => false, 'error' => 'Site not found.'];
        }

        $customerCount = $this->companies->where('site_id', $id)->countAllResults();
        if ($customerCount > 0) {
            return ['success' => false, 'error' => "Cannot delete: {$customerCount} customer(s) are assigned to this site."];
        }

        $this->sites->delete($id);
        $this->activity->log('customer_sites', 'deleted', $actingUserId, "Deleted site #{$id}", (string) $id);

        return ['success' => true];
    }

    public function assignCustomer(int $siteId, int $companyId, ?int $actingUserId): array
    {
        $site = $this->sites->find($siteId);
        if (! $site) {
            return ['success' => false, 'error' => 'Site not found.'];
        }

        $company = $this->companies->find($companyId);
        if (! $company) {
            return ['success' => false, 'error' => 'Customer not found.'];
        }

        if ((int) ($company['site_id'] ?? 0) === $siteId) {
            return ['success' => false, 'error' => 'That customer is already assigned to this site.'];
        }

        $this->companies->update($companyId, [
            'site_id'    => $siteId,
            'updated_by' => $actingUserId,
        ]);

        $this->activity->log(
            'customer_sites',
            'assigned',
            $actingUserId,
            "Assigned customer #{$companyId} ({$company['name']}) to site #{$siteId}",
            (string) $siteId
        );

        return ['success' => true];
    }

    public function unassignCustomer(int $siteId, int $companyId, ?int $actingUserId): array
    {
        $company = $this->companies->find($companyId);
        if (! $company) {
            return ['success' => false, 'error' => 'Customer not found.'];
        }

        if ((int) ($company['site_id'] ?? 0) !== $siteId) {
            return ['success' => false, 'error' => 'That customer is not assigned to this site.'];
        }

        $this->companies->update($companyId, [
            'site_id'    => null,
            'updated_by' => $actingUserId,
        ]);

        $this->activity->log(
            'customer_sites',
            'unassigned',
            $actingUserId,
            "Removed customer #{$companyId} ({$company['name']}) from site #{$siteId}",
            (string) $siteId
        );

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'        => trim($input['name']),
            'site_type'   => trim($input['site_type'] ?? '') ?: null,
            'address'     => trim($input['address'] ?? '') ?: null,
            'city'        => trim($input['city'] ?? '') ?: null,
            'country'     => trim($input['country'] ?? '') ?: null,
            'description' => trim($input['description'] ?? '') ?: null,
            'status'      => $input['status'] ?? 'active',
            'notes'       => $input['notes'] ?: null,
        ];
    }
}
