<?php

declare(strict_types=1);

namespace FatBottom\Services;

use FatBottom\Core\Database;

final class CustomerService
{
    public function __construct(private readonly Database $db)
    {
    }

    public function capture(array $customer, ?int $userId): int
    {
        $email = strtolower(trim((string) $customer['customer_email']));
        $record = $this->db->fetch('SELECT * FROM customers WHERE email = ?', [$email]);
        if ($record === null) {
            $this->db->execute(
                'INSERT INTO customers (user_id, email, full_name, phone) VALUES (?, ?, ?, ?)',
                [
                    $userId,
                    $email,
                    (string) $customer['customer_name'],
                    (string) $customer['customer_phone'],
                ]
            );
            return (int) $this->db->pdo()->lastInsertId();
        }

        $this->db->execute(
            'UPDATE customers SET user_id = ?, full_name = ?, phone = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?',
            [
                $userId ?: ((int) ($record['user_id'] ?? 0) ?: null),
                (string) $customer['customer_name'],
                (string) $customer['customer_phone'],
                (int) $record['id'],
            ]
        );
        return (int) $record['id'];
    }

    public function refresh(int $customerId): void
    {
        $this->db->execute(
            'UPDATE customers SET
                order_count = (SELECT COUNT(*) FROM orders WHERE customer_id = ?),
                lifetime_value_cents = COALESCE((SELECT SUM(total_cents) FROM orders WHERE customer_id = ?), 0),
                first_order_at = (SELECT MIN(placed_at) FROM orders WHERE customer_id = ?),
                last_order_at = (SELECT MAX(placed_at) FROM orders WHERE customer_id = ?),
                updated_at = CURRENT_TIMESTAMP
             WHERE id = ?',
            [$customerId, $customerId, $customerId, $customerId, $customerId]
        );
    }
}
