<?php

namespace Modules\Sale\Services;

use App\Models\ActivityLogModel;
use App\Models\PriceListItemModel;
use App\Models\PriceListModel;

class PriceListService
{
    protected PriceListModel $lists;
    protected PriceListItemModel $items;
    protected ActivityLogModel $activity;

    public function __construct()
    {
        $this->lists    = new PriceListModel();
        $this->items    = new PriceListItemModel();
        $this->activity = new ActivityLogModel();
    }

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

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

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

        $id = (int) $this->lists->getInsertID();
        $this->items->replaceForList($id, $input['lines'] ?? []);
        $this->activity->log('price_lists', 'created', $actingUserId, "Created price list #{$id} ({$data['name']})", (string) $id);

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

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

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

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

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

        $this->items->replaceForList($id, $input['lines'] ?? []);
        $this->activity->log('price_lists', 'updated', $actingUserId, "Updated price list #{$id}", (string) $id);

        return ['success' => true];
    }

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

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

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

        $this->items->where('price_list_id', $id)->delete();
        $this->lists->delete($id);
        $this->activity->log('price_lists', 'deleted', $actingUserId, "Deleted price list #{$id}", (string) $id);

        return ['success' => true];
    }

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