<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\CompetitorModel;

class CompetitorService
{
    protected CompetitorModel $competitors;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->competitors = new CompetitorModel();
        $this->activity    = new ActivityLogModel();
    }

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

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

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

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

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

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

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

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

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

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

        return ['success' => true];
    }

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

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

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

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

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'       => trim($input['name']),
            'website'    => trim($input['website'] ?? '') ?: null,
            'strengths'  => $input['strengths'] ?: null,
            'weaknesses' => $input['weaknesses'] ?: null,
            'status'     => $input['status'] ?? 'active',
            'notes'      => $input['notes'] ?: null,
        ];
    }
}
