import type { PaginatedResponse } from '$lib/types';
import { api } from '$lib/api';

export interface Location {
	id: number;
	location_code: string;
	location_description: string | null;
	company_id: number;
	tenant_id: number;
}

export interface LocationCreate {
	location_code: string;
	location_description?: string | null;
}

export interface LocationUpdate {
	location_description?: string | null;
}

export interface LocationListResponse extends PaginatedResponse {
	items: Location[];
}

export interface LocationFilters {
	location_code?: string;
	location_description?: string;
	page?: number;
	page_size?: number;
}

import { portsApi, PortType } from './ports';

export async function getLocations(
	companyId: number,
	filters?: LocationFilters
): Promise<LocationListResponse> {
	const res = await portsApi.list(companyId, filters || {});
	return (res.data || res) as unknown as LocationListResponse;
}

export async function getLocation(
	locationId: number,
	companyId: number
): Promise<Location> {
	const res = await portsApi.get(locationId, companyId);
	return (res.data || res) as unknown as Location;
}

export async function createLocation(
	data: LocationCreate,
	companyId: number
): Promise<Location> {
	const res = await portsApi.create({
		port_code: data.location_code,
		location_code: data.location_code,
		description: null,
		location_description: data.location_description || null,
		port_type: PortType.ENTRY
	}, companyId);
	return (res.data || res) as unknown as Location;
}

export async function updateLocation(
	locationId: number,
	data: LocationUpdate,
	companyId: number
): Promise<Location> {
	const res = await portsApi.update(locationId, {
		location_description: data.location_description
	}, companyId);
	return (res.data || res) as unknown as Location;
}

export async function deleteLocation(
	locationId: number,
	companyId: number
): Promise<void> {
	await portsApi.delete(locationId, companyId);
}