<?php

namespace App\Repositories\Domain\Write;

use App\Models\Domain;
use App\Repositories\WriteRepository;

class DomainWriteRepository extends WriteRepository
{
    protected function getCacheTag(): string
    {
        return 'domains';
    }

    protected function getReadRepositoryClass(): string
    {
        return \App\Repositories\Domain\Read\DomainReadRepository::class;
    }

    public function activateDomain(Domain $domain): bool
    {
        $domain->is_active = true;
        $result = $domain->save();
        $this->clearRelatedCache($domain);

        return $result;
    }

    public function deactivateDomain(Domain $domain): bool
    {
        $domain->is_active = false;
        $result = $domain->save();
        $this->clearRelatedCache($domain);

        return $result;
    }

    public function updateUsage(Domain $domain): bool
    {
        $domain->last_used_at = now();
        $domain->checked_at = now();
        $result = $domain->save();
        $this->clearRelatedCache($domain);

        return $result;
    }

    public function updateCheckedAt(Domain $domain): bool
    {
        $domain->checked_at = now();
        $result = $domain->save();
        $this->clearRelatedCache($domain);

        return $result;
    }

    public function setExpiration(Domain $domain, ?\DateTime $endsAt = null): bool
    {
        $domain->ends_at = $endsAt;
        $result = $domain->save();
        $this->clearRelatedCache($domain);

        return $result;
    }

    public function bulkActivate(array $domainIds): int
    {
        $updated = Domain::whereIn('id', $domainIds)->update(['is_active' => true]);
        $this->clearCache();

        return $updated;
    }

    public function bulkDeactivate(array $domainIds): int
    {
        $updated = Domain::whereIn('id', $domainIds)->update(['is_active' => false]);
        $this->clearCache();

        return $updated;
    }

    public function updateDailyMailboxLimit(Domain $domain, int $limit): bool
    {
        $domain->daily_mailbox_limit = $limit;
        $result = $domain->save();
        $this->clearRelatedCache($domain);

        return $result;
    }

    public function createWithDefaults(array $data): Domain
    {
        $defaults = [
            'is_active' => true,
            'daily_mailbox_limit' => 100,
            'checked_at' => now(),
        ];

        $domainData = array_merge($defaults, $data);

        return $this->create($domainData);
    }
}
