<?php

namespace App\Services;

use App\Models\Role;
use App\Repositories\OrganizationRepository;
use App\Repositories\UserRepository;
use App\Support\Uuid;
use Illuminate\Support\Facades\Hash;
use App\Services\SopTemplateService;

class AuthService
{
    protected $orgRepo;
    protected $userRepo;

    public function __construct()
    {
        $this->orgRepo = new OrganizationRepository();
        $this->userRepo = new UserRepository();
    }

    public function register(array $data): array
    {
        $ownerRole = Role::where('name', 'owner')->first();

        $organization = $this->orgRepo->create([
            'id' => Uuid::uuid7Binary(),
        ]);

        $user = $this->userRepo->create([
            'id' => Uuid::uuid7Binary(),
            'name' => $data['name'],
            'display_name' => $data['display_name'] ?? null,
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
            'organization_id' => $organization->id,
            'role_id' => $ownerRole->id,
        ]);

        $organization->update(['owner_id' => $user->id]);

        // Seed default SOP data for new organization
        app(SopTemplateService::class)->seedForOrganization($organization);

        return [
            'user' => $user,
            'organization' => $organization,
        ];
    }
}