<?php

namespace Modules\Inventory\Services;

use App\Models\ActivityLogModel;
use App\Models\ProductModel;

class ProductService
{
    protected ProductModel $products;
    protected ActivityLogModel $activity;

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

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

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

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

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

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

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

        $sku = strtoupper(trim($input['sku'] ?? ''));
        if ($this->products->isSkuTaken($sku, $id)) {
            return ['success' => false, 'errors' => ['sku' => 'That SKU is already in use.']];
        }

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

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

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

        return ['success' => true];
    }

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

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

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

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

        return ['success' => true];
    }

    protected function mapInput(array $input): array
    {
        return [
            'name'          => trim($input['name']),
            'barcode'       => trim($input['barcode'] ?? '') ?: null,
            'category_id'   => ($input['category_id'] ?? '') !== '' ? (int) $input['category_id'] : null,
            'brand_id'      => ($input['brand_id'] ?? '') !== '' ? (int) $input['brand_id'] : null,
            'unit_id'       => ($input['unit_id'] ?? '') !== '' ? (int) $input['unit_id'] : null,
            'description'   => $input['description'] ?: null,
            'cost_price'    => (float) ($input['cost_price'] ?? 0),
            'sale_price'    => (float) ($input['sale_price'] ?? 0),
            'reorder_level' => (float) ($input['reorder_level'] ?? 0),
            'status'        => $input['status'] ?? 'active',
            'notes'         => $input['notes'] ?: null,
        ];
    }
}
